//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.cmd;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;

public class GMProto {
    private static final Logger logger = LoggerFactory.getLogger(GMProto.class);
    public static String rootUrl = null;

    public GMProto() {
    }

    static {
        String dir = System.getProperty("user.dir");
        File dirFile = new File(dir);
        //rootUrl =  dirFile.getParent() +"\\IP005";
        rootUrl =  dirFile.getParent();
    }

    public static void toProto() {
        long start = System.currentTimeMillis();
        boolean flag = false;
        System.err.println("路径=>" + rootUrl);

        //rootUrl = rootUrl + "\\IP005";
        try {
//            String pbUrl = rootUrl + "\\soccer3-proto\\proto\\";
//            String targetTxtUrl = rootUrl + "\\soccer3-proto\\proto\\proto\\proto.txt";

            String pbUrl = rootUrl + "\\protocol\\proto\\";
            String targetTxtUrl = rootUrl + "\\protocol\\proto\\proto.txt";

            System.err.println("路径=>" + rootUrl);
            System.err.println("pbUrl路径=>" + pbUrl);
            System.err.println("targetTxtUrl路径=>" + targetTxtUrl);
            Map<String, FileModel> sourceMap = getFiles(pbUrl);

            String pbUrl1 = rootUrl + "\\protocol\\src\\main\\resources\\";
            Map<String, FileModel> sourceMap1 =  getFiles(pbUrl1);

            List<Map.Entry<String, FileModel>> lstEntry = new ArrayList(sourceMap.entrySet());
            Collections.sort(lstEntry, (o1, o2) -> {
                return ((String)o1.getKey()).compareTo((String)o2.getKey());
            });

            List<Map.Entry<String, FileModel>> lstEntry1 = new ArrayList(sourceMap1.entrySet());
            Collections.sort(lstEntry1, (o1, o2) -> {
                return ((String)o1.getKey()).compareTo((String)o2.getKey());
            });

            LinkedHashMap<String, FileModel> linkedHashMap = new LinkedHashMap();
            lstEntry.forEach((o) -> {
                linkedHashMap.put(o.getKey(), o.getValue());
            });
            lstEntry1.forEach((o) -> {
                if (o.getKey().endsWith(".proto")){
                    linkedHashMap.put(o.getKey(), o.getValue());
                }
            });


            Map<String, FileModel> changeMap = new HashMap();
            StringBuffer stringBuffer = new StringBuffer();
            Map<String, String> stringMap = redTxt(targetTxtUrl); // I:\project\IP005\protocol\proto\proto.txt
            System.err.println("*************************************原有的文件大小：=>" + stringMap.size());
            Iterator var11 = linkedHashMap.entrySet().iterator();

            while(true) {
                Map.Entry entry;
                String key;
                while(true) {
                    if (!var11.hasNext()) {
                        if (changeMap.size() > 0) {
                            System.out.println("开始转换 proto -> java \n");
                            AtomicBoolean isSuccess = new AtomicBoolean(true);
                            run(pbUrl1, changeMap, isSuccess);
                            if (!isSuccess.get()) {
                                System.err.println("------------------------------------------------------------------------- \n");
                                return;
                            }

                            flag = true;
                        } else {
                            System.out.println("协议没有改动 pb不需要转换!!!!");
                        }

                        if (flag) {
                            writeTxt(targetTxtUrl, stringBuffer.toString());
                        }

                        System.err.println("\n ********************转换pb数：" + changeMap.size() + " *******总耗时: " + (System.currentTimeMillis() - start) + " ms \n\n");
                        return;
                    }

                    entry = (Map.Entry)var11.next();
                    key = ((FileModel)entry.getValue()).getFile().getName();
                    String md5 = (String)stringMap.getOrDefault(key, null);
                    if (md5 != null && ((FileModel)entry.getValue()).getMd5().equals(md5)) {
                        break;
                    }

                    if (((FileModel)entry.getValue()).getFile().isFile() && !((FileModel)entry.getValue()).getFile().getName().equals("proto.json") && !((FileModel)entry.getValue()).getFile().getName().equals("proto.txt")) {
                        changeMap.put(entry.getKey().toString(), (FileModel)entry.getValue());
                        break;
                    }
                }

                stringBuffer.append(key).append(":").append(((FileModel)entry.getValue()).getMd5()).append("\n");
            }
        } catch (Exception var15) {
            var15.printStackTrace();
        }
    }

    public static Map<String, String> redTxt(String path) {
        StringBuilder result = new StringBuilder();
        Map<String, String> maps = new HashMap();
        File file = new File(path);

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String s = null;

            while((s = br.readLine()) != null) {
                String str = System.lineSeparator() + s;
                result.append(str);
                if (str != null) {
                    Pattern p = Pattern.compile("\\s*|\\t|\\r|\\n");
                    Matcher m = p.matcher(str);
                    str = m.replaceAll("");
                }

                String[] arr = str.split(":");
                if (arr.length == 2) {
                    maps.put(arr[0], arr[1]);
                }
            }

            br.close();
        } catch (Exception var9) {
            var9.printStackTrace();
        }

        return maps;
    }

    public static void writeTxt(String path, String context) {
        try {
            File file = new File(path);
            FileOutputStream fileOutputStream = null;
            if (!file.exists()) {
                file.createNewFile();
            }
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(context.getBytes("utf-8"));
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception var4) {
            var4.printStackTrace();
        }
    }

    public static String readJsonFile(File jsonFile) {
        String jsonStr = "";
        logger.info("————开始读取" + jsonFile.getPath() + "文件————");

        try {
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            StringBuffer sb = new StringBuffer();

            int ch;
            while((ch = reader.read()) != -1) {
                sb.append((char)ch);
            }

            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            logger.info("————读取" + jsonFile.getPath() + "文件结束!————");
            return jsonStr;
        } catch (Exception var6) {
            logger.info("————读取" + jsonFile.getPath() + "文件出现异常，读取失败!————");
            var6.printStackTrace();
            return null;
        }
    }

    public static void writeJsonFile(String path, String json) {
        PrintStream stream = null;

        try {
            stream = new PrintStream(path);
            stream.print(json);
        } catch (IOException var4) {
            var4.printStackTrace();
        }

    }

    public static void run(String source, Map<String, FileModel> changeMap, AtomicBoolean isSuccess) {
        Process process = null;
        InputStream in = null;
        BufferedReader br = null;

        try {
            Iterator var6 = changeMap.entrySet().iterator();

            while(var6.hasNext()) {
                Map.Entry<String, FileModel> entry = (Map.Entry)var6.next();
                String param3 = source + ((FileModel)entry.getValue()).getFile().getName();
                String createProto = rootUrl + "\\protoc.exe --proto_path=" + source + " --java_out=" + rootUrl + "\\protocol\\src\\main\\java\\ " + param3;
                process = Runtime.getRuntime().exec(createProto);
                in = process.getErrorStream();
                br = new BufferedReader(new InputStreamReader(in, "GB2312"));
                String line = null;
                StringBuffer b = new StringBuffer();
                // I:\project\IP005\protoc.exe
                // --proto_path=I:\project\IP005\protocol\src\main\resources\
                // --java_out=I:\project\IP005\protocol\src\main\java\ I:\project\IP005\protocol\src\main\resources\proto_with_route.proto
                while((line = br.readLine()) != null) {
                    b.append(line + "\n");
                }

                if (process.waitFor() != 0) {
                    System.err.println("协议转换失败     => " + ((FileModel)entry.getValue()).getFile().getName());
                    System.err.println(" ===> " + b.toString());
                    isSuccess.set(false);
                    return;
                }

                // 源目录文件
                String sourcePath = param3;
                String savePath = "I:\\TabsProjects\\IP004_Res\\Program\\ProtoBuff\\"+((FileModel)entry.getValue()).getFile().getName();// 文件保存到d盘的file目录下
                File savefile = new File(savePath);
                FileCopyUtils.copy(new File(sourcePath), savefile);

                System.out.println("协议转换成功 并且移动成功 => " + ((FileModel)entry.getValue()).getFile().getName() + " 返回值：" + process.waitFor());
            }
        } catch (Exception var32) {
            var32.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception var31) {
                    var31.printStackTrace();
                }
            }

            if (process != null) {
                try {
                    process.getInputStream().close();
                    process.getOutputStream().close();
                } catch (Exception var30) {
                    var30.printStackTrace();
                }
            }

            if (br != null) {
                try {
                    br.close();
                } catch (Exception var29) {
                    var29.printStackTrace();
                }
            }

        }

    }

    private static Map<String, FileModel> getFiles(String path) throws IOException {
        Map<String, FileModel> map = new HashMap();
        File folder = new File(path);
        Object[] files = getFileList(folder).toArray();
        Arrays.sort(files);
        Object[] var4 = files;
        int var5 = files.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            Object obj = var4[var6];
            File file = (File)obj;
            String key = file.getAbsolutePath().replaceAll("\\\\", "/");
            String md5 = "";
            if (file.isFile()) {
                md5 = DigestUtils.md5DigestAsHex(new FileInputStream(file));
            }

            FileModel fileModel = new FileModel(file, md5);
            map.put(key, fileModel);
        }

        return map;
    }

    private static List<File> getFileList(File folder) {
        List<File> list = new ArrayList();
        File[] files = folder.listFiles();
        File[] var3 = files;
        int var4 = files.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            File file = var3[var5];
            list.add(file);
            if (file.isDirectory()) {
                List<File> fileList = getFileList(file);
                list.addAll(fileList);
            }
        }

        return list;
    }

}
